package add;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import db.DBManager;

public class AddServlet extends HttpServlet {
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		perform(req,resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		perform(req,resp);
	}
	
	private void perform(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException{
		resp.setContentType("text/html;charset=UTF-8");
		req.setCharacterEncoding("UTF-8");
	
		StringBuffer msg = new StringBuffer();//エラーメッセージ
		
		

		Connection con = null;
		Statement stm = null;
		
		String name = req.getParameter("name");//登録する名前
		String password = req.getParameter("password");//登録するパスワード
		
		
		
		if(name == null || name.length()==0){
			msg.append("氏名を入力してください。<br>");
		}
		
		if(password == null || password.length()==0){
			msg.append("passwordを入力してください。<br>");
		}
		
		if(msg.length()==0){
			
			try{
				con = DBManager.getConnection();
				stm = con.createStatement();
				
				String sql = "insert into UserAccount(name,password) values (?,?)";
				PreparedStatement ps = con.prepareStatement(sql);
				
				ps.setString(1, name);
				ps.setString(2, password);
				
				
				ps.executeUpdate();
				ps.close();
				stm.close();
				con.close();
				resp.sendRedirect("index.jsp");
			}
		
			catch(SQLException e){
				e.printStackTrace();
			}
			
		}
		else{
			req.setAttribute("msg", msg.toString());
			RequestDispatcher dispatcher = req.getRequestDispatcher("add.jsp");
			dispatcher.forward(req, resp);
		}
		
	
	
	}
}
